package com.crm.miaohe.service;

import com.crm.miaohe.common.ApplicationConstant;
import com.crm.miaohe.controller.PageResponse;
import com.crm.miaohe.controller.erp.response.Taocan;
import com.crm.miaohe.controller.erp.response.Wuliao;
import com.crm.miaohe.controller.strategy.request.MultiPriceStrategyParams;
import com.crm.miaohe.controller.strategy.request.PriceStrategyParams;
import com.crm.miaohe.controller.strategy.request.PriceStrategyQueryParams;
import com.crm.miaohe.controller.strategy.response.PriceStrategyDetail;
import com.crm.miaohe.controller.strategy.response.PriceStrategyItemGroup;
import com.crm.miaohe.entity.dto.KingdeeQueryParam;
import com.crm.miaohe.exception.ErpBusinessException;
import com.crm.miaohe.mapper.TblPriceStrategyItemMapper;
import com.crm.miaohe.mapper.TblPriceStrategyMapper;
import com.crm.miaohe.model.*;
import com.crm.miaohe.utils.CustomK3CloudApi;
import com.crm.miaohe.utils.StringUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;
import com.google.gson.Gson;
import com.kingdee.bos.webapi.sdk.QueryParam;
import lombok.extern.slf4j.Slf4j;
import net.minidev.json.JSONArray;
import org.springframework.beans.BeanUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PathVariable;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class PriceStrategyServiceImpl implements PriceStrategyService {

    private final TblPriceStrategyMapper priceStrategyMapper;

    private final TblPriceStrategyItemMapper priceStrategyItemMapper;

    private final CustomK3CloudApi api;

    public PriceStrategyServiceImpl(TblPriceStrategyMapper priceStrategyMapper,
                                    TblPriceStrategyItemMapper priceStrategyItemMapper, CustomK3CloudApi api) {
        this.priceStrategyMapper = priceStrategyMapper;
        this.priceStrategyItemMapper = priceStrategyItemMapper;
        this.api = api;
    }

    @Override
    public List<PriceStrategyItemGroup> strategyItems(Long strategyId) {

        TblPriceStrategy priceStrategy = priceStrategyMapper.selectByPrimaryKey(strategyId);
        if (Objects.isNull(priceStrategy)) {
            log.error("Current strategy does not exist. strategyId: {}", strategyId);
            throw new ErpBusinessException(HttpStatus.BAD_REQUEST, ApplicationConstant.STRATEGY_NOT_EXISTS, strategyId);
        }

        //价格策略被锁定  TODO测试20211228
        if (priceStrategy.getIsLocked() != null && priceStrategy.getIsLocked()) {
            throw new ErpBusinessException(HttpStatus.BAD_REQUEST, ApplicationConstant.STRATEGY_IS_LOCKED, strategyId);
        }

        TblPriceStrategyItemExample example = new TblPriceStrategyItemExample();
        example.createCriteria().andStrategyIdEqualTo(strategyId);
        List<TblPriceStrategyItem> items = priceStrategyItemMapper.selectByExample(example);
        Map<String, List<TblPriceStrategyItem>> maps = items.stream()
                .collect(Collectors.groupingBy(TblPriceStrategyItem::getCategoryName));

        List<PriceStrategyItemGroup> list = new ArrayList<>();
        for (String key : maps.keySet()) {
            PriceStrategyItemGroup itemGroup = new PriceStrategyItemGroup();
            itemGroup.setCategoryName(key);
            itemGroup.setPriceStrategyItems(maps.get(key));
            list.add(itemGroup);
        }
        return list;
    }

    @Override
    public List<TblPriceStrategy> strategies(Boolean approved) {
        TblPriceStrategyExample example = new TblPriceStrategyExample();
        example.setOrderByClause("create_time desc,is_default desc");
        if (!ObjectUtils.isEmpty(approved)) {
            example.createCriteria().andApprovedEqualTo(approved);
        }

        return priceStrategyMapper.selectByExample(example);
    }

    @Override
    public List<TblPriceStrategy> defaultStrategies() {
        TblPriceStrategyExample example = new TblPriceStrategyExample();
        example.createCriteria().andApprovedEqualTo(true).andIsDefaultEqualTo(true);
        return priceStrategyMapper.selectByExample(example);
    }

    @Override
    public PageResponse<TblPriceStrategy> getPriceStrategies(PriceStrategyQueryParams params) {
        TblPriceStrategyExample example = new TblPriceStrategyExample();
        TblPriceStrategyExample.Criteria criteria = example.createCriteria();
        if (!ObjectUtils.isEmpty(params.getStrategyName())) {
            criteria.andStrategyNameLike(StringUtils.quoteWith(params.getStrategyName(), "%"));
        }
        if (!ObjectUtils.isEmpty(params.getApproved())) {
            criteria.andApprovedEqualTo(params.getApproved());
        }

        if (!ObjectUtils.isEmpty(params.getIsDefault())) {
            criteria.andIsDefaultEqualTo(params.getIsDefault());
        }

        PageInfo<TblPriceStrategy> pageInfo =
                PageHelper.startPage(params.getPageNo(), params.getPageSize(), "create_time desc,is_default desc")
                        .doSelectPageInfo(() -> priceStrategyMapper.selectByExample(example));

        return PageResponse.<TblPriceStrategy>builder()
                .currentPage(pageInfo.getPageNum())
                .totalPage(pageInfo.getPages())
                .totalElement(pageInfo.getTotal())
                .records(pageInfo.getList())
                .build();
    }

    @Override
    public PriceStrategyDetail getStrategyDetail(Long strategyId) {
        TblPriceStrategy priceStrategy = priceStrategyMapper.selectByPrimaryKey(strategyId);
        if (Objects.isNull(priceStrategy)) {
            log.error("Current strategy does not exist. strategyId: {}", strategyId);
            throw new ErpBusinessException(HttpStatus.BAD_REQUEST, ApplicationConstant.STRATEGY_NOT_EXISTS, strategyId);
        }
        TblPriceStrategyItemExample example = new TblPriceStrategyItemExample();
        example.createCriteria().andStrategyIdEqualTo(strategyId);
        List<TblPriceStrategyItem> items = priceStrategyItemMapper.selectByExample(example);
        return PriceStrategyDetail.builder()
                .strategyId(priceStrategy.getId())
                .strategyName(priceStrategy.getStrategyName())
                .remark(priceStrategy.getRemark())
                .items(items)
                .build();
    }

    @Override
    @Transactional
    public void addPriceStrategy(PriceStrategyParams params) {
        TblPriceStrategy tblPriceStrategy = new TblPriceStrategy();
        BeanUtils.copyProperties(params, tblPriceStrategy);
        priceStrategyMapper.insertSelective(tblPriceStrategy);

        // 获取当前时间
        LocalDateTime now = LocalDateTime.now();
        String currentUser = Optional.ofNullable(SecurityContextHolder.getContext().getAuthentication().getName()).orElse("anonymousUser");
        List<TblPriceStrategyItem> items = params.getItems().stream().map(data -> {
            TblPriceStrategyItem strategyItem = new TblPriceStrategyItem();
            strategyItem.setStrategyId(tblPriceStrategy.getId());
            strategyItem.setCategoryCode(data.getCategoryCode());
            strategyItem.setCategoryName(data.getCategoryName());
            strategyItem.setProductCode(data.getProductCode());
            strategyItem.setProductName(data.getProductName());
            strategyItem.setPrice(data.getPrice());
            strategyItem.setSpecNum(data.getSpecNum());//料包特殊数量
            strategyItem.setMoqTimes(data.getMoqTimes());
            strategyItem.setMoq(data.getMoq());
            strategyItem.setStopSell(data.getStopSell());

            //如果是套餐，则取出套餐内的明细放入
            if (data.getCategoryName().equals("套餐")) {
                List<Taocan> taocanList = getTaocanDetails(data.getProductCode());
                String temp = getTaocanDetails(taocanList);
                strategyItem.setSpecCode(temp);
                if (taocanList != null && taocanList.size() > 0) {
                    strategyItem.setTaocanDetail(JSONArray.toJSONString(taocanList));
                }
            } else {
                strategyItem.setSpecCode(data.getSpecCode());
            }

            strategyItem.setSpecName(data.getSpecName());
            strategyItem.setFbaseUnitIdfname(data.getFbaseUnitIdfname());
            strategyItem.setLiaobao(data.getLiaobao());
            strategyItem.setZhacai(data.getZhacai());
            strategyItem.setXiangcong(data.getXiangcong());
            strategyItem.setLajiaoyou(data.getLajiaoyou());
            strategyItem.setXiaohuntun(data.getXiaohuntun());
            strategyItem.setMoqTimes(data.getMoqTimes());
            strategyItem.setMoq(data.getMoq());
            strategyItem.setStopSell(data.getStopSell());
            strategyItem.setCreateTime(now);
            strategyItem.setUpdateTime(now);
            strategyItem.setCreateUser(currentUser);
            strategyItem.setUpdateUser(currentUser);
            strategyItem.setVersion(0L);
            return strategyItem;
        }).collect(Collectors.toList());
        priceStrategyItemMapper.insertBatch(items);
    }

    @Override
    @Transactional
    public void copyPriceStrategy(PriceStrategyParams params) {
        TblPriceStrategy strategy = priceStrategyMapper.selectByPrimaryKey(params.getStrategyId());
        strategy.setId(0L);
        strategy.setStrategyName(params.getStrategyName());
        strategy.setApproved(false);

        priceStrategyMapper.insertSelective(strategy);

        //Copy 价格策略项目
        TblPriceStrategyItemExample example = new TblPriceStrategyItemExample();
        example.createCriteria().andStrategyIdEqualTo(params.getStrategyId());

        //获取到价格策略项目同时保存
        LocalDateTime now = LocalDateTime.now();
        String currentUser = Optional.ofNullable(SecurityContextHolder.getContext().getAuthentication().getName()).orElse("anonymousUser");
        List<TblPriceStrategyItem> items = priceStrategyItemMapper.selectByExample(example).stream().map(item -> {
            TblPriceStrategyItem strategyItem = new TblPriceStrategyItem();
            strategyItem.setStrategyId(strategy.getId());
            strategyItem.setCategoryCode(item.getCategoryCode());
            strategyItem.setCategoryName(item.getCategoryName());
            strategyItem.setProductCode(item.getProductCode());
            strategyItem.setProductName(item.getProductName());
            strategyItem.setPrice(item.getPrice());
            strategyItem.setSpecNum(item.getSpecNum());//料包特殊数量
            strategyItem.setMoqTimes(item.getMoqTimes());
            strategyItem.setMoq(item.getMoq());
            strategyItem.setStopSell(item.getStopSell());

            //如果是套餐，则取出套餐内的明细放入
            if (item.getCategoryName().equals("套餐")) {
                List<Taocan> taocanList = getTaocanDetails(item.getProductCode());
                String temp = getTaocanDetails(taocanList);
                strategyItem.setSpecCode(temp);
                if (taocanList != null && taocanList.size() > 0) {
                    strategyItem.setTaocanDetail(JSONArray.toJSONString(taocanList));
                }
            } else {
                strategyItem.setSpecCode(item.getSpecCode());
            }

            strategyItem.setSpecName(item.getSpecName());
            strategyItem.setFbaseUnitIdfname(item.getFbaseUnitIdfname());
            strategyItem.setLiaobao(item.getLiaobao());
            strategyItem.setZhacai(item.getZhacai());
            strategyItem.setXiangcong(item.getXiangcong());
            strategyItem.setLajiaoyou(item.getLajiaoyou());
            strategyItem.setXiaohuntun(item.getXiaohuntun());
            strategyItem.setMoqTimes(item.getMoqTimes());
            strategyItem.setMoq(item.getMoq());
            strategyItem.setStopSell(item.getStopSell());
            strategyItem.setCreateTime(now);
            strategyItem.setUpdateTime(now);
            strategyItem.setCreateUser(currentUser);
            strategyItem.setUpdateUser(currentUser);
            strategyItem.setVersion(0L);
            return strategyItem;
        }).collect(Collectors.toList());
        priceStrategyItemMapper.insertBatch(items);
    }

    @Override
    @Transactional
    public void updatePriceStrategy(PriceStrategyParams params) {
        TblPriceStrategy strategy = priceStrategyMapper.selectByPrimaryKey(params.getStrategyId());
        strategy.setStrategyName(params.getStrategyName());
        strategy.setRemark(params.getRemark());
        strategy.setIsDefault(params.getIsDefault() != null);
        strategy.setIsLocked(params.getIsLocked() != null);
        strategy.setApproved(false);
        priceStrategyMapper.updateByPrimaryKeySelective(strategy);
        // 删除Item，重新添加
        TblPriceStrategyItemExample example = new TblPriceStrategyItemExample();
        example.createCriteria().andStrategyIdEqualTo(params.getStrategyId());
        int count = priceStrategyItemMapper.deleteByExample(example);
        log.info("{} items are deleted.", count);
        LocalDateTime now = LocalDateTime.now();
        String currentUser = Optional.ofNullable(SecurityContextHolder.getContext().getAuthentication().getName()).orElse("anonymousUser");
        List<TblPriceStrategyItem> items = params.getItems().stream().map(item -> {
            TblPriceStrategyItem strategyItem = new TblPriceStrategyItem();
            strategyItem.setStrategyId(strategy.getId());
            strategyItem.setCategoryCode(item.getCategoryCode());
            strategyItem.setCategoryName(item.getCategoryName());
            strategyItem.setProductCode(item.getProductCode());
            strategyItem.setProductName(item.getProductName());
            strategyItem.setPrice(item.getPrice());
            strategyItem.setSpecNum(item.getSpecNum());//料包特殊数量
            strategyItem.setMoqTimes(item.getMoqTimes());
            strategyItem.setMoq(item.getMoq());
            strategyItem.setStopSell(item.getStopSell());

            //如果是套餐，则取出套餐内的明细放入
            if (item.getCategoryName().equals("套餐")) {
                List<Taocan> taocanList = getTaocanDetails(item.getProductCode());
                String temp = getTaocanDetails(taocanList);
                strategyItem.setSpecCode(temp);
                if (taocanList != null && taocanList.size() > 0) {
                    strategyItem.setTaocanDetail(JSONArray.toJSONString(taocanList));
                }
            } else {
                strategyItem.setSpecCode(item.getSpecCode());
            }

            strategyItem.setSpecName(item.getSpecName());
            strategyItem.setFbaseUnitIdfname(item.getFbaseUnitIdfname());
            strategyItem.setLiaobao(item.getLiaobao());
            strategyItem.setZhacai(item.getZhacai());
            strategyItem.setXiangcong(item.getXiangcong());
            strategyItem.setLajiaoyou(item.getLajiaoyou());
            strategyItem.setXiaohuntun(item.getXiaohuntun());
            strategyItem.setMoqTimes(item.getMoqTimes());
            strategyItem.setMoq(item.getMoq());
            strategyItem.setStopSell(item.getStopSell());
            strategyItem.setCreateTime(now);
            strategyItem.setUpdateTime(now);
            strategyItem.setCreateUser(currentUser);
            strategyItem.setUpdateUser(currentUser);
            strategyItem.setVersion(0L);
            return strategyItem;
        }).collect(Collectors.toList());
        priceStrategyItemMapper.insertBatch(items);
    }

    @Override
    public void updateMultiPriceStrategy(MultiPriceStrategyParams params) {

        //需要修改的价格策略
        var strategyIds = params.getStrategyIds();
        //价格策略详情
        var priceStrategyItem = params.getItem();
        //根据价格策略ID查询出所有的价格策略明细
        TblPriceStrategyItemExample example = new TblPriceStrategyItemExample();
        example.createCriteria().andStrategyIdIn(strategyIds);
        List<TblPriceStrategyItem> lists = priceStrategyItemMapper.selectByExample(example);

        Map<Long, List<TblPriceStrategyItem>> map = lists.stream().collect(Collectors.toMap(TblPriceStrategyItem::getStrategyId, p -> {
                    List<TblPriceStrategyItem> list = new ArrayList<>();
                    list.add(p);
                    return list;
                },
                (List<TblPriceStrategyItem> value1, List<TblPriceStrategyItem> value2) -> {
                    value1.addAll(value2);
                    return value1;
                }
        ));

        TblPriceStrategyItem item = new TblPriceStrategyItem();
        item.setPrice(priceStrategyItem.getPrice());
        item.setLiaobao(priceStrategyItem.getLiaobao());
        item.setSpecNum(priceStrategyItem.getSpecNum());
        item.setZhacai(priceStrategyItem.getZhacai());
        item.setLajiaoyou(priceStrategyItem.getLajiaoyou());
        item.setXiangcong(priceStrategyItem.getXiangcong());
        item.setXiaohuntun(priceStrategyItem.getXiaohuntun());
        item.setProductCode(priceStrategyItem.getProductCode());
        item.setProductName(priceStrategyItem.getProductName());
        item.setCategoryCode(priceStrategyItem.getCategoryCode());
        item.setCategoryName(priceStrategyItem.getCategoryName());
        item.setSpecName(priceStrategyItem.getSpecName());
        item.setFbaseUnitIdfname(priceStrategyItem.getFbaseUnitIdfname());

        for (Long key : map.keySet()) {
            if (map.get(key).stream().filter(p -> p.getCategoryCode().equals(priceStrategyItem.getCategoryCode()) && p.getProductCode().equals(priceStrategyItem.getProductCode())).count() > 0) {
                //修改价格策略明细信息
                TblPriceStrategyItemExample cond = new TblPriceStrategyItemExample();
                cond.createCriteria()
                        .andCategoryCodeEqualTo(priceStrategyItem.getCategoryCode())
                        .andProductCodeEqualTo(priceStrategyItem.getProductCode())
                        .andStrategyIdEqualTo(key);
                priceStrategyItemMapper.updateByExampleSelective(item, cond);
            } else {
                item.setStrategyId(key);
                //增加一条价格策略明细信息
                priceStrategyItemMapper.insertSelective(item);
            }
        }
    }

    @Override
    public void updateMultiMoqStrategy(MultiPriceStrategyParams params) {
        log.info("价格策略，倍数{}，起订量{}", params.getItem().getMoqTimes(), params.getItem().getMoq());
        //需要修改的价格策略
        var strategyIds = params.getStrategyIds();
        //价格策略详情
        var priceStrategyItem = params.getItem();
        // 物料分类
        String categoryCode = priceStrategyItem.getCategoryCode();
        // 物料编码
        String productCode = priceStrategyItem.getProductCode();
        // 物料编码
        long moqTimes = priceStrategyItem.getMoqTimes();
        // 物料编码
        long moq = priceStrategyItem.getMoq();

        LocalDateTime now = LocalDateTime.now();
        String currentUser = Optional.ofNullable(SecurityContextHolder.getContext().getAuthentication().getName()).orElse("anonymousUser");

        priceStrategyItemMapper.updateMoq(strategyIds, categoryCode, productCode, moqTimes, moq, currentUser, now);
    }

    @Override
    public void updateMultiStopSellStrategy(MultiPriceStrategyParams params) {
        log.info("价格策略，暂停报货{}", params.getItem().getStopSell());
        //需要修改的价格策略
        var strategyIds = params.getStrategyIds();
        //价格策略详情
        var priceStrategyItem = params.getItem();
        // 物料分类
        String categoryCode = priceStrategyItem.getCategoryCode();
        // 物料编码
        String productCode = priceStrategyItem.getProductCode();
        // 暂停报货
        boolean stopSell = priceStrategyItem.getStopSell();

        LocalDateTime now = LocalDateTime.now();
        String currentUser = Optional.ofNullable(SecurityContextHolder.getContext().getAuthentication().getName()).orElse("anonymousUser");

        priceStrategyItemMapper.updateStopSell(strategyIds, categoryCode, productCode, stopSell, currentUser, now);
    }

    @Override
    @Transactional
    public List<String> updatePriceStrategyCategoryCode() {
        String filter = "FUseOrgId=1";
        List<Wuliao> datas = null;
        List<String> result = new ArrayList<>();
        try {
            datas = api.executeBillQuery(
                    new QueryParam().setFormId("BD_MATERIAL")
                            .setFieldKeys("FMATERIALID,FName,FSpecification,FNumber,FMATERIALGROUP,FMATERIALGROUP.FName,FMATERIALGROUP.FNumber")
                            .setFilterString(filter)
                            .setOrderString("FNumber"),
                    Wuliao.class);


            //抽出目前系统有的商品code和分类code
            List<TblPriceStrategyItem> list = priceStrategyItemMapper.selectProductCodeAndCategoryCode();

            int length = 0;
            int taocanLength = 0;
            //更新CategoryCode
            for (Wuliao wuliao : datas) {
                String categoryCode = "";
                if (StringUtil.isNotEmpty(wuliao.getFMATERIALGROUP())) {
                    categoryCode = wuliao.getFMATERIALGROUP().split("\\.")[0];
                }
                String finalCategoryCode = categoryCode;

                //全量更新,商品Code一样
                List<TblPriceStrategyItem> itemList = list.stream().filter(p -> p.getProductCode().equals(wuliao.getFNumber())).collect(Collectors.toList());
                boolean needUpdated = false;
                for(TblPriceStrategyItem itemObj: itemList) {
                    String wuliaoSpec = wuliao.getFSpecification() == null? "": wuliao.getFSpecification();
                    String priceStrategySpec = itemObj.getSpecName() == null? "": itemObj.getSpecName();
                    if (!"套餐".equals(wuliao.getFMATERIALGROUPFName())
                            && finalCategoryCode.equals(itemObj.getCategoryCode())
                            && wuliao.getFMATERIALGROUPFName().equals(itemObj.getCategoryName())
                            && wuliao.getFName().equals(itemObj.getProductName())
                            && wuliaoSpec.equals(priceStrategySpec)) {
                        //  分组编码，分组编码名称，物料名称没有变化时，不更新, 套餐必刷
                    } else {
                        needUpdated = true;
                        break;
                    }
                }

                if (needUpdated) {
//                    if ("好歹馄饨泡沫箱".equals(item.getProductName())) {
//                        System.out.println("");
//                    }
//                    String wuliaoSpec = wuliao.getFSpecification() == null? "": wuliao.getFSpecification();
//                    String priceStrategySpec = item.getSpecName() == null? "": item.getSpecName();
//                    if (!"套餐".equals(wuliao.getFMATERIALGROUPFName())
//                            && finalCategoryCode.equals(item.getCategoryCode())
//                            && wuliao.getFMATERIALGROUPFName().equals(item.getCategoryName())
//                            && wuliao.getFName().equals(item.getProductName())
//                            && wuliaoSpec.equals(priceStrategySpec)) {
//                        //  分组编码，分组编码名称，物料名称没有变化时，不更新, 套餐必刷
//                        continue;
//                    }
                    length++;
                    if ("套餐".equals(wuliao.getFMATERIALGROUPFName())) {
                        taocanLength++;
                    }
//                    result.add(String.format("物料:%s[%s]->分类:%s[%s]", wuliao.getFName(), wuliao.getFNumber(), wuliao.getFMATERIALGROUPFName(), finalCategoryCode));
                    TblPriceStrategyItemExample example = new TblPriceStrategyItemExample();
                    example.createCriteria().andProductCodeEqualTo(wuliao.getFNumber());
                    TblPriceStrategyItem tblPriceStrategyItem = new TblPriceStrategyItem();
                    tblPriceStrategyItem.setCategoryCode(finalCategoryCode);
                    tblPriceStrategyItem.setCategoryName(wuliao.getFMATERIALGROUPFName());
                    tblPriceStrategyItem.setProductName(wuliao.getFName());
                    tblPriceStrategyItem.setProductCode(wuliao.getFNumber());
                    tblPriceStrategyItem.setSpecName(wuliao.getFSpecification());
                    if ("套餐".equals(wuliao.getFMATERIALGROUPFName())) {
                        List<Taocan> taocanList = getTaocanDetails(wuliao.getFNumber());
                        if (taocanList != null && taocanList.size() > 0) {
                            String temp = getTaocanDetails(taocanList);
                            tblPriceStrategyItem.setSpecCode(temp);
                            tblPriceStrategyItem.setTaocanDetail(JSONArray.toJSONString(taocanList));
                        }
                    }
                    priceStrategyItemMapper.updateByExampleSelective(tblPriceStrategyItem, example);
                }
            }
            result.add("更新物料" + length + "件, 其中套餐" + taocanLength + "件!");
        } catch (Exception e) {
            log.error("价格策略更新失败", e);
            throw new ErpBusinessException(HttpStatus.BAD_REQUEST, ApplicationConstant.KINGDEE_001, e.getMessage());
        }
        return result;
    }

    @Override
    @Transactional
    public void deletePriceStrategy(Long strategyId) {
        // 删除价格策略
        int count = priceStrategyMapper.deleteByPrimaryKey(strategyId);
        log.info("价格策略删除成功，删除个数：[{}]", count);
        // 删除Items
        TblPriceStrategyItemExample example = new TblPriceStrategyItemExample();
        example.createCriteria().andStrategyIdEqualTo(strategyId);
        count = priceStrategyItemMapper.deleteByExample(example);
        log.info("价格策略Item删除成功，删除个数：[{}]", count);
    }

    @Override
    public void approvedPriceStrategy(Long strategyId) {
        TblPriceStrategy tblPriceStrategy = new TblPriceStrategy();
        tblPriceStrategy.setApproved(true);
        tblPriceStrategy.setId(strategyId);
        priceStrategyMapper.updateByPrimaryKeySelective(tblPriceStrategy);
    }

    //获得套餐明细
    public List<Taocan> getTaocanDetails(String parentId) {
        try {
            KingdeeQueryParam p = new KingdeeQueryParam();
            p.setSubSystemId("23");
            return api.executeBillQuery(
                    p.setFormId("ENG_BOM")
                            .setFieldKeys("FMATERIALIDCHILD,FCHILDITEMNAME,FCHILDITEMMODEL,FNUMERATOR,FBPStoreUnitID,F_DLMH_ZXWLFZ,F_DLMH_ZXWLFZMC")
                            .setFilterString("FMATERIALID.FNumber = '" + parentId + "' and FUseOrgId = 1 "),
                    Taocan.class);
        } catch (Exception e) {
            throw new ErpBusinessException(HttpStatus.BAD_REQUEST, ApplicationConstant.KINGDEE_001, e.getMessage());
        }
    }

    //获得套餐明细
    public String getTaocanDetails(List<Taocan> datas) {
        String temp = "";
        if (datas != null) {
            for (int i = 0; i < datas.size(); i++) {
                temp = temp + datas.get(i).getFCHILDITEMNAME() + " " + datas.get(i).getFNUMERATOR().intValue() + datas.get(i).getFBPStoreUnitID() + " ";
            }
        }
        return temp;
    }
}
